package org.dromara.module.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vdurmont.emoji.EmojiParser;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.exception.TransactionalException;
import org.dromara.common.core.utils.MathUtil;
import org.dromara.common.core.utils.OrderUtil;
import org.dromara.module.domain.*;
import org.dromara.module.mapper.ProductAttrValueMapper;
import org.dromara.module.mapper.ProductMapper;
import org.dromara.module.mapper.ProductOrderInfoMapper;
import org.dromara.module.mapper.ProductOrderMapper;
import org.dromara.module.service.IProductOrderInfoService;
import org.dromara.module.service.IProductOrderService;
import org.dromara.module.service.IProductService;
import org.dromara.module.service.ParameterService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 订单Service业务层处理
 *
 * @author Mr.Zhou
 * @date 2024-10-21
 */
@RequiredArgsConstructor
@Service
public class ProductOrderServiceImpl extends ServiceImpl<ProductOrderMapper, ProductOrder> implements IProductOrderService {

    @Resource
    private ProductOrderInfoMapper productOrderInfoMapper;
    @Resource
    private IProductOrderInfoService productOrderInfoService;
    @Resource
    private ProductAttrValueMapper productAttrValueMapper;
    @Resource
    private ProductOrderMapper productOrderMapper;
    @Resource
    private ProductMapper productMapper;
    @Resource
    private IProductService productService;
    @Resource
    private ParameterService parameterService;


    @Value("${ruoyi.imgUrl}")
    private String imgPrefix;//图片地址
    @Value("${ruoyi.profile}")
    private String uploadPath;

    @Override
    public ProductOrder getOrderDetail(long orderId) {
        ProductOrder order = productOrderMapper.selectById(orderId);
        if(order != null){
            List<ProductOrderInfo> infos = productOrderInfoService.selectListByOrderId(order.getId());
            if(infos != null && infos.size() > 0){
                for(ProductOrderInfo orderInfo : infos){
                    if(StrUtil.isNotEmpty(orderInfo.getQrCode())){
                        orderInfo.setQrCode(imgPrefix + orderInfo.getQrCode());
                    }
                    Product product = productService.getProductInfoById(orderInfo.getProductId());
                    if(product != null){
                        orderInfo.setProductName(product.getProductName());
                        orderInfo.setImgUrl(product.getImage());
                    }

                    ProductAttrValue sku = productAttrValueMapper.selectById(orderInfo.getSkuId());
                    if(sku != null){
                        orderInfo.setAttrValue(sku);
                        if(StrUtil.isEmpty(orderInfo.getSkuName())) {
                            orderInfo.setSkuName(sku.getSku());
                        }
                    }
                }
            }
            order.setInfos(infos);
            if(!StrUtil.isNotEmpty(order.getRealName())){
                order.setRealName(EmojiParser.parseToUnicode(order.getRealName()));
            }
            order.setTotalPayMoney(new BigDecimal(MathUtil.getDoubleUp(order.getPayPrice().doubleValue())));
            order.setOutTradeNo("");
        }
        return order;
    }

    /**
     * 更新订单的状态
     * @return
     */
    @Override
    public int updateOrderState(ProductOrder order, int state) {
        order.setStatus(state);
        return productOrderMapper.updateById(order);
    }

    /**
     * 买家查订单
     * @param userId
     * @param state
     * @param pageIndex
     * @param pageSize
     * @return
     */
    @Override
    public List<ProductOrder> queryListByUserId(int userId,int order_type, int state, int pageIndex, int pageSize) {
        QueryWrapper<ProductOrder> qw1 = new QueryWrapper<>();
        qw1.eq("user_id",userId);
        qw1.eq("is_del",0);

        /**
         * 订单状态 0 - 未支付   1 - 支付中  2 - 已支付（待核销）  3 - 已核销  4 - 已评价  5 - 订单取消
         * 6 - 发起退货  7 - 同意退货  8 - 退货完成  9 - 拒绝退货  10 - 团购成功 11 - 团购失败
         */
        if(state != -1){
            if(state == 0){
                Integer[] states = {0,1};
                qw1.in("status", Arrays.asList(states));
            } else if(state == 8){
                qw1.in("status", 6,7,8,9);
            } else {
                qw1.eq("status",state);
            }
        }
        qw1.orderByDesc("create_time");
        List<ProductOrder> list = productOrderMapper.getPageEntityList(qw1,pageIndex,pageSize);
        if(list != null && list.size() > 0){
            for(ProductOrder order : list){

//                order.setImgUrl(imgPrefix + mer.getShopLogo());
                order.setRealName(EmojiParser.parseToUnicode(order.getRealName()));

                QueryWrapper<ProductOrderInfo> qwInfos = new QueryWrapper<>();
                qwInfos.eq("order_id", order.getId());
                qwInfos.eq("state",1);
                qwInfos.eq("is_del", 0);
                List<ProductOrderInfo> infos = productOrderInfoMapper.selectList(qwInfos);
                if(CollUtil.isNotEmpty(infos)){
                    for (ProductOrderInfo info : infos){
                        Product product = productService.getProductInfoById(info.getProductId());
                        if(product!=null){
                            info.setProductName(product.getProductName());
                            info.setImgUrl(product.getImage());
                        }

                        if(StrUtil.isEmpty(info.getSkuName())) {
                            ProductAttrValue attrValue = productAttrValueMapper.selectById(info.getSkuId());
                            if (attrValue != null) {
                                info.setSkuName(attrValue.getSku());
                            }
                        }
                    }
                }
                order.setInfos(infos);
            }
        }
        return list;
    }

    @Transactional
    @Override
    public long buyNow(WxUser user, int order_type, int count, ProductAttrValue attrValue, String remark,String platform) throws TransactionalException {
        try{
            double allPrice = 0;
            double d1Total = 0, d2Total = 0, d3Total = 0, dTotalFee = 0, dTotalSettlement = 0;
            allPrice = count * attrValue.getPrice().doubleValue();

            Product product = productMapper.selectById(attrValue.getProductId());

            Parameter parameter = parameterService.getParameterById(1);

            String payNo = OrderUtil.getPayNo();
            //添加 订单表数据
            ProductOrder order = new ProductOrder();
            String orderNo = OrderUtil.getOrderNoByTimes();
            if(platform.equals("wxmini")){
                order.setPlatform(0);
            }else{
                order.setPlatform(1);
            }
            order.setPayNo(payNo);
            order.setOrderNo(orderNo);
            order.setOutTradeNo(orderNo);

            //订单类型  0 - 平台商品类  1 - 设备上的商品类  2 - 线下商家活动  3 - 商家优惠券 4 - 团购类
            order.setOrderType(order_type);
            order.setUserId(user.getId());
            order.setTotalPrice(new BigDecimal(allPrice));
            order.setCreateTime(new Date());
            order.setTotalNum(count);
            order.setNickName(EmojiParser.parseToUnicode(user.getNickName()));
            order.setPayType(parameter.getProductPayPlatform());
            order.setPayPlatformId(0);
            order.setPayPrice(new BigDecimal(allPrice));
            order.setFee(new BigDecimal(allPrice * 0.06 / 100));
            order.setStatus(0);//订单状态 0 - 未支付  1 - 支付中  2 - 已支付 3 - 待发货  4 - 待收货  5 - 待评价 6 - 已评价  7 - 订单取消  8 - 退货中 9 - 已退款
            order.setRemark(remark);
            order.setUserPhone(user.getPhoneNum());
            order.setRealName(user.getNickName());
            int ret = productOrderMapper.insert(order);
            if(ret <= 0){
                throw new TransactionalException("product order insert error");
            }else{
                long order_id = order.getId();
                for (int i = 0; i < count;i++){
                    ProductOrderInfo orderInfo = new ProductOrderInfo();
                    orderInfo.setCount(1);
                    orderInfo.setProductId(attrValue.getProductId());
                    orderInfo.setOrderId(order_id);
                    orderInfo.setSinglePrice(attrValue.getPrice());
                    orderInfo.setOriginPrice(attrValue.getOtPrice());
                    orderInfo.setTotalMoney(attrValue.getPrice());
                    orderInfo.setActivityMinsMoney(new BigDecimal(0));
                    orderInfo.setState(1);
                    orderInfo.setSkuId(attrValue.getId());
                    orderInfo.setVerifyCode(OrderUtil.getVerfiyNoAndRandom());//核销码
                    orderInfo.setVerifyCount(0);
                    orderInfo.setIsVerify(0);
                    orderInfo.setIsDel(0);
                    orderInfo.setOpSysUserId(0);
                    orderInfo.setDelSysUserId(0L);
                    orderInfo.setSettlementState(0);
                    ret = productOrderInfoMapper.insert(orderInfo);
                    if(ret <=0){
                        throw new TransactionalException("product order info insert error");
                    }
                }
                ret = productOrderMapper.updateById(order);
                if(ret <= 0){
                    throw new TransactionalException("productOrderMapper insert error");
                }
            }
            return order.getId();
        }catch (Exception ex){
            ex.printStackTrace();
            throw new TransactionalException("UserSignRecord insert error");
        }
    }

    /**
     *  支付成功后的 订单信息处理
     * @param order
     * @return
     * @throws TransactionalException
     */
    @Override
    @Transactional
    public int buyNormalUpdate(ProductOrder order, WxUser user) throws TransactionalException{
        int ret = 0;
        try{
            //减库存
            QueryWrapper<ProductOrderInfo> qwInfo = new QueryWrapper<>();
            qwInfo.eq("order_id",order.getId());
            qwInfo.eq("is_del", 0);
            List<ProductOrderInfo> orderInfos = productOrderInfoMapper.selectList(qwInfo);
            for (ProductOrderInfo orderInfo : orderInfos){
                ProductAttrValue attrValue = productAttrValueMapper.selectById(orderInfo.getSkuId());
                if(attrValue != null){
                    int count = orderInfo.getCount();
                    int attrCount = attrValue.getStock();
                    int saleCount = attrValue.getSales();
                    attrValue.setSales(saleCount + orderInfo.getCount());
                    ret =  productAttrValueMapper.updateById(attrValue);
                    if(ret <=0){
                        throw new TransactionalException("productAttrValueMapper updateById error");
                    }
                    int countProduct = 0;
                    Product product = productMapper.selectById(orderInfo.getProductId());
                    if(product != null){
                        countProduct = product.getSales();
                        product.setSales(countProduct + orderInfo.getCount());
                        ret = productMapper.updateById(product);
                        if(ret <=0){
                            throw new TransactionalException("productMapper updateById error");
                        }
                    }
                }
            }

            //更改订单支付状态
            ret = productOrderMapper.updateById(order);
            if(ret <= 0){
                throw new TransactionalException("productOrderMapper updateById error");
            }
        }catch (Exception e){
            e.printStackTrace();
            throw new TransactionalException("userIntegralRecordMapper insert error");
        }
        return ret;
    }

}
